import axios from "axios";
const CancelToken = axios.CancelToken;
const pending = new Map();
let TOKEN = localStorage.getItem('ALB_H5_TOKEN')
const getType = function (data) {
  return Object.prototype.toString.call(data).match(/\s(\w+)/)[1]
}

// 将formdata中的数据转为对象
function expandFormData (form) {
  let data = {}
  for (let [k, v] of form.entries()) {
    if (!['File', 'Undefined'].includes(getType(v))) {
      data[k] = v
    }
  }
  return data
}
class HttpRequest {
  constructor(url) {
    this.baseURL = process.env[`VUE_APP_${url}_URL`];
    this.withCredentials = true;
    this.timeout = 10000;
  }
  // 中间件
  middleRequest(options = {}) {
    const instance = axios.create();
    const config = {
      ...options,
      baseURL: this.baseURL,
      timeout: this.timeout,
      withCredentials: this.withCredentials,
    };
    this.setInterceptors(instance, options.url);
    return instance(config);
  }
  // GET
  get(url, params, options = {}) {
    const GET = this.middleRequest({
      method: "get",
      url: url,
      params: {
        ...params,
        user_token: TOKEN
      },
      responseType: options.isBolb ? 'blob' : '',
      ...options,
    });
    return GET;
  }
  // POST
  post(url, params, options = {}) {
    const POST = this.middleRequest({
      method: "post",
      url: url,
      data: {
        ...params,
        user_token: TOKEN
      },
      ...options
    });
    return POST;
  }
  // POST
  put(url, params, options = {}) {
    const PUT = this.middleRequest({
      method: "put",
      url: url,
      data: {
        ...params,
        user_token: TOKEN
      },
      ...options
    });
    return PUT;
  }
  // 撤销重复请求
  changePending(config) {
    const url = [config.method, config.url].join("&");
    config.cancelToken = config.cancelToken || new CancelToken((cancel) => {
      if (pending.has(url)) {
        pending.set(url, cancel);
      } else if (pending.has(url)) {
        const cancel = pending.get(url);
        cancel(url);
        pending.delete(url);
      }
    });
  }
  // 清空清空
  clearPending() {
    for (const [url, cancel] of this.pending) {
      cancel(url);
    }
    this.pending.clear();
  }

  // 拦截器
  setInterceptors(instance) {
    this.requestInterceptors(instance);
    this.responseInterceptors(instance);
  }
  // 请求拦截器
  requestInterceptors(instance) {
    instance.interceptors.request.use(
      (config) => {
        this.changePending(config);
        // config.headers.Authorization = window.localStorage.getItem('ALB_H5_TOKEN')
        return config;
      },
      (err) => Promise.reject(err)
    );
  }
  // 响应拦截器
  responseInterceptors(instance) {
    instance.interceptors.response.use((response) => {
        this.changePending(response.config);
        // 是否是返回的二进制的下载文件
        if (response.data instanceof Blob) {
          return response.data
        }
        if (response.data.code === 0) {
          return Promise.resolve(response.data.data);
        } else if ([10003].includes(response.data.code)) {
          // 10003: token失效
          localStorage.removeItem('ALB_H5_TOKEN')
          window.location.href = window.location.origin + '/'
          return Promise.reject(response.data);
        } else {
          return Promise.reject(response.data);
        }
      },
      (err) => {
        return Promise.reject(err.response.data);
      }
    );
  }
}
 const HTTP_METHODS = new HttpRequest();
 const HTTP_ALB =new HttpRequest('ALB');
 export {
  HTTP_METHODS,
  HTTP_ALB
 }